﻿(function (module) {

    var ctrl = function ($log, $parse, $scope, $timeout, $rootScope) {
        var source = [{
            firstName: 'Mauro',
            lastName: 'Servienti',
            dataType: 'people'
        }, {
            firstName: 'Enos',
            lastName: 'Recanati',
            dataType: 'people'
        }, {
            firstName: 'Andrea',
            lastName: 'Saltarello',
            dataType: 'people'
        }, {
            companyName: 'topics.it',
            dataType: 'companies'
        }, {
            companyName: 'Managed Designs S.r.l.',
            dataType: 'companies'
        }];

        $scope.selectedItem = null;
        $scope.searchResults = [];
        $scope.searchTerm = '';

        $scope.executeSearch = function (term) {
            var results = _.filter(source, function (t) {
                if (t.dataType === 'people') {
                    return t.firstName.toLowerCase().indexOf(term.toLowerCase()) === 0 
                        || t.lastName.toLowerCase().indexOf(term.toLowerCase()) === 0;
                } else if (t.dataType === 'companies') {
                    return t.companyName.toLowerCase().indexOf(term.toLowerCase()) === 0;
                }
                return false;
            });

            var promise = $timeout(function () {
                $rootScope.safeApply($scope, function () {
                    $log.debug('results:', results);
                    $scope.searchResults = results;
                });

                return results;
            }, 300).then(function (results) {
                return results;
            });

            return promise;
        };
        $scope.selectItem = function (item) {
            $log.debug('select invoked on: ', item);
            $rootScope.safeApply($scope, function () {
                $scope.selectedItem = item;
            });
        };
    };
    ctrl.$inject = ['$log', '$parse', '$scope', '$timeout', '$rootScope'];
    module.controller('typeaheadWithTemplatesController', ctrl);

}(angular.module('topics.controllers')));